package com.elizabeth;

import org.jfree.chart.annotations.CategoryAnnotation;
import org.jfree.chart.annotations.TextAnnotation;
import org.jfree.chart.axis.CategoryAnchor;
import org.jfree.chart.axis.CategoryAxis;
import org.jfree.chart.axis.ValueAxis;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.plot.Plot;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.text.TextUtils;
import org.jfree.chart.ui.RectangleEdge;
import org.jfree.chart.util.Args;
import org.jfree.chart.util.PublicCloneable;
import org.jfree.data.category.CategoryDataset;

import java.awt.*;
import java.awt.geom.Rectangle2D;
import java.awt.image.ImageObserver;
import java.io.Serializable;

public class CategoryImageAnnotation extends TextAnnotation implements CategoryAnnotation, Cloneable, PublicCloneable, Serializable {

    private static final long serialVersionUID = 3333360090781320148L;
    private Comparable category;
    private CategoryAnchor categoryAnchor;
    private double value;
    private double angle;
    private Image image;

    public CategoryImageAnnotation(String label,Image image, Comparable category, double value, double angle) {
        super(label);
        Args.nullNotPermitted(category, "category");
        this.category = category;
        this.value = value;
        this.image = image;
        this.angle = angle;
        this.categoryAnchor = CategoryAnchor.MIDDLE;
    }

    @Override
    public void draw(Graphics2D g2, CategoryPlot plot, Rectangle2D dataArea, CategoryAxis domainAxis, ValueAxis rangeAxis) {

        CategoryDataset dataset = plot.getDataset();
        int catIndex = dataset.getColumnIndex(this.category);
        int catCount = dataset.getColumnCount();
        float anchorX = 0.0F;
        float anchorY = 0.0F;
        PlotOrientation orientation = plot.getOrientation();
        RectangleEdge domainEdge = Plot.resolveDomainAxisLocation(plot.getDomainAxisLocation(), orientation);
        RectangleEdge rangeEdge = Plot.resolveRangeAxisLocation(plot.getRangeAxisLocation(), orientation);
        if (orientation == PlotOrientation.HORIZONTAL) {
            anchorY = (float)domainAxis.getCategoryJava2DCoordinate(this.categoryAnchor, catIndex, catCount, dataArea, domainEdge);
            anchorX = (float)rangeAxis.valueToJava2D(this.value, dataArea, rangeEdge);
        } else if (orientation == PlotOrientation.VERTICAL) {
            anchorX = (float)domainAxis.getCategoryJava2DCoordinate(this.categoryAnchor, catIndex, catCount, dataArea, domainEdge);
            anchorY = (float)rangeAxis.valueToJava2D(this.value, dataArea, rangeEdge);
        }

        g2.setFont(this.getFont());
        g2.setPaint(this.getPaint());
        TextUtils.drawRotatedString(this.getText(), g2, anchorX, anchorY, this.getTextAnchor(), this.getRotationAngle(), this.getRotationAnchor());
        g2.drawImage(this.image, (int)(anchorX-angle), (int)anchorY, null);


    }
}
